import java.util.ArrayList;
import java.util.List;

import org.hibernate.Transaction;
import org.hibernate.classic.Session;


public class Method {

	public static Video saveVideo(Video video)
	{
		Transaction tms = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			tms = session.beginTransaction();
        	session.save(video);
        	session.getTransaction().commit();
		}catch (RuntimeException e) {
			if (tms != null)
				tms.rollback();
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		return video;
	}
	
	public static void saveKeywords(ArrayList<KeywordsVideo> keywordsList)
	{
		Transaction tms = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			tms = session.beginTransaction();
	        for (KeywordsVideo keywords : keywordsList){
	        	session.save(keywords);
	        }
        	session.getTransaction().commit();
		}catch (RuntimeException e) {
			if (tms != null)
				tms.rollback();
			
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
	}
	
	public static void saveURL(String url)
	{
		Transaction tms = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			tms = session.beginTransaction();
			url = url.split("&amp;")[0];
			Liens l = new Liens(url);
			session.save(l);
			session.getTransaction().commit();
		} catch (RuntimeException e) {
			if (tms != null) {
				tms.rollback();
			}

			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
	}
	
	public static boolean isVideoInDB(String id)
	{
		Transaction trns = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		
		try {
			trns = session.beginTransaction();
			// LIMIT 1
			List<Liens> li = session.createQuery("FROM Video as v WHERE v.videoID =:strId").setString("strId", id).list();
			
			trns.commit();

			if(li.size() > 0){
				return true;
			}
		}
		
		catch (RuntimeException e) {
			if (trns != null) {
				trns.rollback();
			}
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		
		return false;
	}
	
	public static boolean isUrlInDB(String url)
	{
		Transaction trns = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		
		try {
			trns = session.beginTransaction();
			url = url.split("&amp;")[0];
			// LIMIT 1
			List<Liens> li = session.createQuery("FROM Liens as l WHERE l.url =:strURL").setString("strURL", url).list();
			
			trns.commit();

			if(li.size() > 0){
				return true;
			}
		}
		catch (RuntimeException e) {
			if (trns != null) {
				trns.rollback();
			}
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		
		return false;
	}
}
